package com.chujian.system.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapBuilder;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chujian.framework.component.EntityInfo;
import com.chujian.framework.core.base.BaseServiceImpl;
import com.chujian.core.entity.CoreClass;
import com.chujian.system.core.mapper.CoreClassMapper;
import com.chujian.system.core.service.CoreClassService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 服务实现类
 *
 * @author chujian
 * @since 2021-08-24
 */
@Service
@Slf4j
public class CoreClassServiceImpl extends BaseServiceImpl<CoreClassMapper, CoreClass> implements CoreClassService {

    public static final String CLASS_TYPE_ENTITY = "entity";
    private static final Map<String, Class<?>> classTypeMap = MapBuilder.<String, Class<?>>create()
            .put(CLASS_TYPE_ENTITY, EntityInfo.class)
            .build();

    @Override
    public void full(List<CoreClass> datas) {
        if (CollUtil.isNotEmpty(datas)) {
            for (CoreClass data : datas) {
                if (null == data) {
                    continue;
                }
                Class<?> objClazz = classTypeMap.get(data.getClassType());
                data.setCfgObj(JSON.parseObject(data.getCfg(), objClazz));
                data.setCfg(null);
            }
        }
    }

    @Override
    public CoreClass saveEntityInfo(EntityInfo info) {
        CoreClass exists = this.getByClassName(info.getEntityClass());
        CoreClass coreClass = new CoreClass()
                .setClassType(CLASS_TYPE_ENTITY)
                .setClassName(info.getEntityClass())
                .setCfg(JSON.toJSONString(info));
        if (null == exists) {
            this.save(coreClass);
        } else {
            coreClass.setClassId(exists.getClassId());
            this.updateById(coreClass);
        }
        return this.getById(coreClass.getClassId());
    }

    @Override
    public CoreClass getByClassName(String className) {
        return this.getOne(
                new LambdaQueryWrapper<CoreClass>()
                        .eq(CoreClass::getClassName, entityClass)
        );
    }
}
